package com.allianz.webapps.ExceptionResolver;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;


public class AjaxAndSimpleMappingExceptionResolver extends SimpleMappingExceptionResolver {

	@Override
	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		ex.printStackTrace();
		ResponseBody responseBody = null;
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			responseBody = handlerMethod.getMethodAnnotation(ResponseBody.class);
		}

		if (responseBody == null) {
			return super.doResolveException(request, response, handler, ex);
		}
		ModelAndView view = new ModelAndView();
		response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		response.setContentType("application/json; charset=utf-8");
		response.setHeader("Cache-Control", "no-cache, must-revalidate");
		PrintWriter writer;
		try {
			writer = response.getWriter();
			writer.write(ex.getMessage());
			writer.flush();
			writer.close();
		} catch (IOException e) {
			logger.error("前端异常操作异常！");
		}
		return view;
	}
}
